package com.mask.eurekaconsumer;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.discovery.EurekaClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;

@RestController
@Slf4j
public class MainController {

	@Autowired
	// 抽象
	DiscoveryClient client;
	
	@Autowired
	EurekaClient client2;
	
	@Autowired
	LoadBalancerClient lb;

	@Autowired
	RestTemplate restTemplate;
	
	

	@GetMapping("/client6")
	@ResponseBody
	public Object client6() {
		
		// ribbon 完成客户端的负载均衡，过滤掉down了的节点
		ServiceInstance instance = lb.choose("eureka-provider");
		
		String url ="http://" + instance.getServiceId() +":"+ instance.getPort() + "/getHi";
		   

		String respStr = restTemplate.getForObject(url, String.class);
		   
		System.out.println("respStr"  + respStr);

		return respStr;
	}

	/**
	 * 手动负载均衡
	 * @return
	 */
	@Autowired
	DiscoveryClient discoveryClient;

	@GetMapping("/client7")
	@ResponseBody
	public Object client7() {
		List<ServiceInstance> instances = discoveryClient.getInstances("eureka-provider");
		log.info("instances:{}",instances);

		//自定义的轮训算法
		//随机
		int nextInt = new Random().nextInt(instances.size());
		ServiceInstance instance = instances.get(nextInt);

		String url ="http://" + instance.getServiceId() +":"+ instance.getPort() + "/getHi";


		String respStr = restTemplate.getForObject(url, String.class);

//		System.out.println("respStr"  + respStr);

		return respStr;
	}


	@GetMapping("/client8")
	@ResponseBody
	public Object client8() {

		ServiceInstance instance = lb.choose("eureka-provider");

		String url ="http://" + instance.getServiceId() +":"+ instance.getPort() + "/getHi";


		String respStr = restTemplate.getForObject(url, String.class);

		log.info("返回结果:{}",respStr);

		return respStr;
	}

	/**
	 * 自动处理一个url
	 * @return
	 */
	@GetMapping("/client9")
	@ResponseBody
	public Object client9() {

//		ServiceInstance instance = lb.choose("eureka-provider");

		String url ="http://eureka-provider/getHi";


		String respStr = restTemplate.getForObject(url, String.class);

		log.info("返回结果client9:{}",respStr);

		return respStr;
	}
}
